package com.tao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tao.dao.AssistMapper;
import com.tao.dto.AssistDto;
import com.tao.entity.Assist;
import com.tao.entity.Help;
import com.tao.entity.User;
import com.tao.enums.AppHttpCodeEnum;
import com.tao.service.HelpService;
import com.tao.service.IAssistService;
import com.tao.service.UserService;
import com.tao.utils.SecurityUtils;
import com.tao.vo.AssistVo;
import com.tao.vo.HelpInfoVo;
import com.tao.vo.ResponseResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zzp
 * @since 2023-05-06
 */
@Service
public class AssistServiceImpl extends ServiceImpl<AssistMapper, Assist> implements IAssistService {
    @Resource
    private AssistMapper assistMapper;

    @Resource
    private HelpService helpService;

    @Resource
    private UserService userService;


    @Override
    public List<Assist> byHelp(Long helpId) {
        return assistMapper.byHelp(helpId);
    }

    @Override
    public Map<String,Object> byAssistant(Integer pageNum,Integer pageSize,Long userId) {
        Map<String,Object> data= new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        List<AssistVo> assists = assistMapper.byAssistant(userId);
        getPageInfo(assists,data);
        return data;
    }

    @Override
    public Assist detail(Integer id) {
        return assistMapper.detail(id);
    }

    @Override
    public boolean checkAssistStatus(Long helpId) {
        List<Assist> assists = assistMapper.getAssistByHelpId(helpId);
        for (Assist assist : assists) {
            if (!(assist.getStatus().equals("2")) || (assist.getStatus().equals("3"))) {
                return false;
            }
        }
        return true;
    }


    @Override
    public ResponseResult finish(AssistDto assistDto) {
        Assist assist = getById(assistDto.getId());
        //协助说明
        assist.setAssistInfo(assistDto.getComment());
        assist.setStatus("1");
        updateById(assist);
        return ResponseResult.okResult(200,"操作成功");
    }

    @Override
    public ResponseResult verify(AssistDto assistDto) {
        Assist assist = getById(assistDto.getId());
        Long createBy1 = assist.getCreateBy();
        Long helpId = assist.getHelpId();
        Help help = helpService.getById(helpId);
        Long createBy2 = help.getCreateBy();
        User user1 = userService.getById(createBy1);
        User user2 = userService.getById(createBy2);
        Integer reward = help.getReward();
        if (!(assist.getStatus().equals("2")) && !(assist.getStatus().equals("3"))){
            //审核说明
            assist.setVerifyInfo(assistDto.getComment());
            if (assistDto.getVerify()){
                if ((user2.getBalance()-reward)<0){
                    return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"余额不足");
                }
                assist.setStatus("2");
                user1.setBalance(user1.getBalance()+reward);
                user2.setBalance(user2.getBalance()-reward);
            }else{
                assist.setStatus("3");
                help.setAssistNum(help.getAssistNum()-1);
            }
            updateById(assist);
            helpService.updateById(help);
            userService.updateById(user1);
            userService.updateById(user2);
            //判断协助人数是否等于需求人数且求助下的所有协助订单的状态是否都是审核通过或者不通过
            if (help.getAssistNum() == help.getNeedNum() && checkAssistStatus(helpId)){
                help.setStatus('1');
                helpService.updateById(help);
                return ResponseResult.okResult(200,"操作成功");
            }
            return ResponseResult.okResult(200,"操作成功");
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"该订单已审核");
        }
    }

    @Override
    public ResponseResult delete(Long id) {
        Assist assist = getById(id);
        Long helpId = assist.getHelpId();
        Help help = helpService.getById(helpId);
        Integer assistNum = help.getAssistNum();
        String s = assist.getStatus();
        if (s.equals("1")){//订单待审核
            return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"订单待审核");

        }else if (s.equals("2")){//订单审核通过
            removeById(id);
            return ResponseResult.okResult(200,"操作成功");
        }else {//订单待完成和审核不通过
            removeById(id);
            help.setAssistNum(assistNum-1);
            helpService.updateById(help);
            return ResponseResult.okResult(200,"操作成功");
        }
    }

    @Override
    public ResponseResult add(Long helpId) {
        Assist assist = new Assist();
        assist.setCreateBy(SecurityUtils.getUserId());
        assist.setHelpId(helpId);
        Help help = helpService.getById(helpId);
        Integer assistNum = help.getAssistNum();
        LambdaQueryWrapper<Assist> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Assist::getCreateBy,SecurityUtils.getUserId());
        lambdaQueryWrapper.eq(Assist::getHelpId, helpId);
        List<Assist> assists = list(lambdaQueryWrapper);
        if (help.getCreateBy ()!= SecurityUtils.getUserId()){
            for (Assist assist1: assists){
                if (!assist1.getStatus().equals("2") && !assist1.getStatus().equals("3")){
                    return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"已接取且尚未完成");
                }
            }
            if (help.getStatus() != '0'){
                return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"该求助已完成");
            }else {
                help.setAssistNum(assistNum+1);
                if (help.getAssistNum()>help.getNeedNum()){
                    return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"超出需求人数");
                }else {
                    save(assist);
                    helpService.updateById(help);
                    return ResponseResult.okResult(200,"操作成功");
                }
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST, "不可以接取自己发布的订单");
        }
    }

    public void getPageInfo(List<AssistVo> assists, Map<String,Object> data){
        PageInfo<AssistVo> pageInfo = new PageInfo<>(assists);
        data.put("total",pageInfo.getTotal());
        data.put("totalPage",pageInfo.getPages());
        data.put("rows",pageInfo.getList());
    }
}
